$(function () {
  //人员管理 打开窗口
  $('.personal-trigger').on('click', function (event) {
    event.preventDefault();
    $('.personal-pop').addClass('is-visible3');
    var n = 1;
    patrollingPersonPageList(1);
    // patrollingPersonPageList(patrollingPersonPageNumCurr);
  });

  // 人员管理 列表展示
  function patrollingPersonPageList(n) {
    var obj = {};
    obj.size = 8;
    obj.page = n - 1;
    var ret = getPatrollingPersonInfo(obj);
    ret.then(function(data){
        console.log(data);
        patrollingPersonPageNum = data.data.totalPages;           
        size =  data.data.size;
        console.log(patrollingPersonPageNum);
        console.log(size);
        var content = data.data.content;
        // 人员总数
        var perSum = data.data.totalElements;
        console.log(perSum);
        $("#personalModal .perSum").find("span").text(perSum);
        // patrollingPersonPageNum = data.data.totalPages;           
        // size =  data.data.size;
        $('#patrollingPersonPageTable .tbodyList').html('');
        for(var i = 0; i < content.length; i++) {
            $('#patrollingPersonPageTable .tbodyList').append('<tr><td><input type="checkbox" class="check" devid="' + content[i].id + '"></td><td>'  + ((n-1)* size + i + 1) + '</td><td>'+ content[i].name +'</td><td>'+ content[i].telephone +'</td><td>'+content[i].organization.orgName+'</td><td><span class="configBtnStyle modifyBtn" id='+ content[i].id +' orgid='+ content[i].organization.id +' modImg='+ content[i].photo +'>修改</span><span class="configBtnStyle focusBtn">重点关注</span><span class="configBtnStyle positionBtn">定位</span></td></tr>'); 
        }
        patrollingPersonPageFunc(patrollingPersonPageNum, n);
    }).catch(function (err) {
        console.log(err);
    });    
  }

  //人员管理  关闭窗口
  $('.personal-pop').on('click', function (event) {
    if ($(event.target).is('.cd-popup-close') || $(event.target).is('.personal-pop')) {
      event.preventDefault();
      $(this).removeClass('is-visible3');
    }
  });

  //设备管理  分页功能
  var patrollingPersonPageNum = 1;
  var patrollingPersonPageNumCurr = 1;
  function patrollingPersonPageFunc(pageSum, startPageNum) {
      console.log(pageSum);
      if (pageSum <= 1) {
        $('#personalModal .pageJump').hide()
      } else {
        $('#personalModal .pageJump').show()
      }
      Page({
          num: pageSum, //页码数
          startnum: startPageNum, //指定页码
          elem: $('#personalPage'), //指定的元素
          callback: function (n) { //回调函数
              patrollingPersonPageNumCurr = n;
              patrollingPersonPageList(n);
              // 当翻到下一页时 清除掉 全选按钮的 选中状态
              $("#patrollingPersonSelectAll").prop("checked", false);
          }
      });
  };


  // 全选 反选
  $("#patrollingPersonSelectAll").on("click", function(){
    var allcheck = $("#patrollingPersonSelectAll").prop("checked");
    $("#personalModal .tbodyList .check").prop("checked", allcheck);
  })
  // 反选
  $("#personalModal .tbodyList").on("click", '.check', function(){
      var length1 = $("#personalModal .tbodyList").find(":checkbox").length;
      var length2 = $("#personalModal .tbodyList").find(":checked").length;
      if(length1 == length2) {
      $("#patrollingPersonSelectAll").prop("checked", true);
      } else {
      $("#patrollingPersonSelectAll").prop("checked", false);
      }
  })
  // 删除
  $("#personalModal .delete").on("click", function(){
    if ($('#patrollingPersonSelectAll').prop("checked")) {
      patrollingPersonPageNumCurr = patrollingPersonPageNumCurr - 1;
    }
    $("#personalModal .tbodyList").find(":checked").each(function(index, ele){
      var id = $(this).attr("devid");
      console.log(id);
      var ret = delPatrollingPersonInfo(id);
      ret.then(function(data){
          console.log(data);
          $("#patrollingPersonSelectAll").prop("checked", false);
          tipModalFunc('删除成功!');
          patrollingPersonPageFunc(patrollingPersonPageNum, patrollingPersonPageNumCurr);
          patrollingPersonPageList(patrollingPersonPageNumCurr);
      }).catch(function (err) {
          console.log(err);
      });
    })  
  })

  // 人员添加 页面显示
  $("#personalModal .addBtn").on("click", function(){
    event.preventDefault();
    $(".patrollingPersonalAdd-pop").addClass("is-visible3");
    // 获取所有 微型消防站
    var getAllfireStationsListRet = getAllfireStationsList();
    getAllfireStationsListRet.then(function (data) {
        console.log(data);
        $('.patrollingPersonalAdd-pop .patrollingPersonAddPageOragList').html('');
        for (var i = 0; i < data.data.length; i++) {
            $('.patrollingPersonalAdd-pop .patrollingPersonAddPageOragList').append('<option value="' + data.data[i].id + '" selected>' + data.data[i].orgName + '</option>')
        }
    }).catch(function (err) {
        console.log(err)
    });
  })

  // 添加页面 关闭
  $(".patrollingPersonalAdd-pop").on("click", function (event) {
    if (
    $(event.target).is(".cd-popup-close") ||
    $(event.target).is(".patrollingPersonalAdd-pop")
    ) {
      event.preventDefault();
      // 清空照片
      formData = {};
      $(".patrollingPersonalAdd-pop input").val('');
      $('#patrollingPersonalAddPage .pic').attr('src', '');
      $("#patrollingPersonalAddPage .pic").css("opacity", 0);
      $('#patrollingPersonalAddPage .pic').removeClass('opacity1');
      $("#patrollingPersonalAddPage").find(".touxiang").addClass("bac");
      $(this).removeClass("is-visible3");

       //Modal验证销毁重构
       $("#patrollingPersonalAddPage").data('bootstrapValidator').destroy();
       $('#patrollingPersonalAddPage').data('bootstrapValidator', null);
       addPatrollingPersonPage();
    }
  });


  // 点击头像 上传图片
  var picThat;
  var formData;
  var multipartFile;
  var file;
  $("#patrollingPersonalAddPage .touxiang").on("click", '.pic', function () {
    console.log(this);
    $(this).parent().find(".upload").click(); 
    $(this).parent().find(".upload").on("change", function (e) {
      var objUrl = getObjectURL(this.files[0]); 
      console.log(objUrl)
      picThat = this;
      console.log(this);

      if (objUrl) {
        $(this).parent().removeClass("bac");
        $(this).parent().find(".pic").css("opacity", 1);
        $(this).parent().find(".pic").attr("src", objUrl); 
        $(this).parent().find(".pic").addClass('opacity1');
      } else {
        $(this).parent().find(".pic").removeClass('opacity1');
      }

      file = picThat.files[0];
      console.log(file);
      multipartFile = new FormData();
      multipartFile.append("multipartFile", file);
      console.log(multipartFile);
    });
  });

  function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
      url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  }

  // 添加页面的 删除头像
  $("#patrollingPersonalAddPage .delTouxiang").on("click", function(){
    $(this).siblings('.pic').attr('src', '');
    multipartFile = {};    
    $(this).siblings('.pic').removeClass('opacity1');
    $("#patrollingPersonalAddPage .pic").css("opacity", 0);
    $("#patrollingPersonalAddPage").find(".touxiang").addClass("bac");
  })

  // 添加 人员管理 
  addPatrollingPersonPage();
  function addPatrollingPersonPage() {
    $("#patrollingPersonalAddPage").bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
          name: {
            validators: {
              notEmpty: {
                message: '姓名不能为空'
              }
            }
          },
          telephone: {
            validators: {
              notEmpty: {
                message: '联系电话不能为空'
              }
            }
          },
          orgId: {
            validators: {
              notEmpty: {
                message: '所属组织不能为空'
              }
            }
          },
        }
      }).on("success.form.bv", function(e){
        e.preventDefault();
        var $form = $(e.target);
        var obj = $form.serializeObject();
        var orgId = $(".patrollingPersonalAdd-pop .patrollingPersonAddPageOragList").val();
        // orgId = Number(orgId);
        // var id = new Date().valueOf();
        // obj.id = id;
        console.log(orgId);
        console.log(obj);
        var ret = getPatrollingPersonSave(orgId, JSON.stringify(obj));
        ret.then(function(data){
            console.log(data);
            console.log(data.data.id);
            // 上传图片
            var id = data.data.id;            
            // 点击提交 提交图片
            $.ajax({
              url: "/patrol/poplePhoto?id="+id,
              type: 'post',
              data: multipartFile,
              contentType: false,
              processData: false,
              success: function (res) {
                console.log(res);
                multipartFile = {};
              },
              error: function (res) {
                console.log(res);
                multipartFile = {};
              }
            });

            // 清除照片
            $('#patrollingPersonalAddPage .pic').attr('src', '');
            $("#patrollingPersonalAddPage .pic").css("opacity", 0);
            $('#patrollingPersonalAddPage .pic').removeClass('opacity1');
            $("#patrollingPersonalAddPage").find(".touxiang").addClass("bac");
            $('.patrollingPersonalAdd-pop').removeClass('is-visible3');
            // Modal验证销毁重构
            $("#patrollingPersonalAddPage").data('bootstrapValidator').destroy();
            $('#patrollingPersonalAddPage').data('bootstrapValidator', null);
            addPatrollingPersonPage();
            $('.patrollingPersonalAdd-pop input').val('');
            patrollingPersonPageList(patrollingPersonPageNumCurr);
            tipModalFunc('添加成功!');
        }).catch(function(err){
            console.log(err);
        });
      })
  }

  // 刷新按钮
  $("#personalModal .refreshStyle").on("click", function(){
    patrollingPersonPageList(1);
  }) 

  // 巡更人员管理 修改页面
  var modId;
  $("#personalModal .tbodyList").on("click", '.modifyBtn', function(){
      event.preventDefault();
      $(".patrollingPersonModify-pop").addClass("is-visible3");
      var name = $(this).parent().parent().find("td").eq(2).text();
      var tel = $(this).parent().parent().find("td").eq(3).text();
      var fireStations = $(this).attr("orgid");
      modId = $(this).attr("id");
      console.log(name);
      console.log(tel);
      console.log(modId);
      $("#patrollingPersonalModifyPage .patrollingPersonalModifyName").val(name);
      $("#patrollingPersonalModifyPage .patrollingPersonalModifyTel").val(tel);
      // 获取所有 微型消防站
      var getAllfireStationsListRet = getAllfireStationsList();
      getAllfireStationsListRet.then(function (data) {
        console.log(data);
          $('.patrollingPersonModify-pop .patrollingPersonAddPageOragList').html('');
          for (var i = 0; i < data.data.length; i++) {
              $('.patrollingPersonModify-pop .patrollingPersonAddPageOragList').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>')
          }
          console.log(fireStations);
          $("#patrollingPersonalModifyPage .patrollingPersonAddPageOragList").val(fireStations);
      }).catch(function (err) {
          console.log(err);
      });   
      
      // 获取巡更人员头像
      var modImgUrl = $(this).attr("modImg");
      console.log(modImgUrl);
      console.log(typeof(modImgUrl));
      if (modImgUrl !== 'null') {
        $("#patrollingPersonalModifyPage .touxiang").removeClass("bac");
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").css("opacity", 1);
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").attr("src", modImgUrl); 
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").addClass('opacity1');      
      } else {
        $("#patrollingPersonalModifyPage .touxiang").addClass("bac");
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").css("opacity", 0);
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").attr("src", ''); 
        $("#patrollingPersonalModifyPage .touxiang").find(".pic").removeClass('opacity1');   
      }
      // if(!modImgUrl) {
      //   $("#patrollingPersonalModifyPage .touxiang").addClass("bac");
      //   $("#patrollingPersonalModifyPage .touxiang").find(".pic").css("opacity", 0);
      //   $("#patrollingPersonalModifyPage .touxiang").find(".pic").attr("src", ''); 
      //   $("#patrollingPersonalModifyPage .touxiang").find(".pic").removeClass('opacity1');   
      // }
     
  })

  // 修改 里面的头像删除
  $("#patrollingPersonalModifyPage .delTouxiang").on("click", function(){
    // 先删除图片样式
    $(this).siblings('.pic').attr('src', '');
    multipartFile = {};    
    $(this).siblings('.pic').removeClass('opacity1');
    $("#patrollingPersonalModifyPage .pic").css("opacity", 0);
    $("#patrollingPersonalModifyPage").find(".touxiang").addClass("bac");
  })

  var picThat;
  var formDataMid;
  // 修改页面的 更新头像
  $("#patrollingPersonalModifyPage .touxiang").on("click", '.pic', function () {
    console.log(this);
    $(this).parent().find(".upload").click(); 
    $(this).parent().find(".upload").on("change", function (e) {
      var objUrl = getObjectURL(this.files[0]); 
      console.log(objUrl)
      picThat = this;
      console.log(this);

      if (objUrl) {
        $(this).parent().removeClass("bac");
        $(this).parent().find(".pic").css("opacity", 1);
        $(this).parent().find(".pic").attr("src", objUrl); 
        $(this).parent().find(".pic").addClass('opacity1');
      } else {
        $(this).parent().find(".pic").removeClass('opacity1');
      }

      file = picThat.files[0];
      console.log(file);
      formDataMid = new FormData();
      formDataMid.append("multipartFile", file);
      console.log(formDataMid);
    });
  });

  // 修改 保存 提交
  function modiftyPatrollingPersonPage() {
    $("#patrollingPersonalModifyPage").bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
          name: {
            validators: {
              notEmpty: {
                message: '姓名不能为空'
              }
            }
          },
          telephone: {
            validators: {
              notEmpty: {
                message: '联系电话不能为空'
              }
            }
          },
          orgId: {
            validators: {
              notEmpty: {
                message: '所属组织不能为空'
              }
            }
          },
        }
      }).on("success.form.bv", function(e){
        e.preventDefault();
        var $form = $(e.target);
        var obj = $form.serializeObject();
        obj.id = modId;
        console.log(modId);
        console.log(obj);
        var orgId = $(".patrollingPersonModify-pop .patrollingPersonAddPageOragList").val();
        var ret = getPatrollingPersonSave(orgId, JSON.stringify(obj));
        ret.then(function(data){
          console.log(data);          
          // 更新头像
          $.ajax({
            url: "/patrol/poplePhoto?id="+modId,
            type: 'post',
            data: formDataMid,
            async: false,
            contentType: false,
            processData: false,
            success: function (res) {
              console.log(res);
              formDataMid = {};
            },
            error: function (res) {
              console.log(res);
              formDataMid = {};
            }
          });
          // 更新 所有数据之后  清除 图片
          $('#patrollingPersonalModifyPage .pic').attr('src', '');
          $("#patrollingPersonalModifyPage .pic").css("opacity", 0);
          $('#patrollingPersonalModifyPage .pic').removeClass('opacity1');
          $("#patrollingPersonalModifyPage").find(".touxiang").addClass("bac");
          $('.patrollingPersonModify-pop').removeClass('is-visible3');       

          // Modal验证销毁重构
          $("#patrollingPersonalModifyPage").data('bootstrapValidator').destroy();
          $('#patrollingPersonalModifyPage').data('bootstrapValidator', null);
          modiftyPatrollingPersonPage();
          $('.patrollingPersonModify-pop input').val('');
          patrollingPersonPageList(patrollingPersonPageNumCurr);
          tipModalFunc('修改成功!');
        }).catch(function(err){
          console.log(err);
        })
      })
  }
  modiftyPatrollingPersonPage();
  // 巡更人员管理 修改页面 关闭
  $(".patrollingPersonModify-pop").on("click", function (event) {
    if (
    $(event.target).is(".cd-popup-close") ||
    $(event.target).is(".patrollingPersonModify-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      $("#patrollingPersonalModifyPage").data('bootstrapValidator').destroy();
      $('#patrollingPersonalModifyPage').data('bootstrapValidator', null);
      modiftyPatrollingPersonPage();
    }
  });
});